import { ACSubscriberHolderSet } from './ACSubscriberHolderSet';

export class ACSubscriber<T> {

  private callback?: (value: T) => void
  private storeToHolderSet?: WeakRef<ACSubscriberHolderSet>;

  constructor(callback: (value: T) => void) {
    this.callback = callback;
  }

  sendValue(value: T) {
    if (this.callback) {
      if (this.isValid()) {
        this.callback(value);
      } else {
        console.warn('ArkCombine', 'ACSubscriber 没有添加到 ACSubscriberHolderSet, 无法收到订阅通知');
       }
     }
  }

  setHolderSet(holderSet: ACSubscriberHolderSet) {
    this.storeToHolderSet = new WeakRef(holderSet);
  }

  isValid(): boolean {
    return (this.storeToHolderSet?.deref() != undefined);
  }

}
